package com.sense.feel.login.utils

import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import android.util.Log
import com.sense.kukoo.common.repo.bean.AreaBean
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.lang.StringBuilder
import java.util.*

/**
 * @Author Lionszhang
 * @Date   2021/3/10 19:15
 * @Name   ReadAssetsJsonUtil.java
 * @Instruction 读取Asserts资源
 */
object ReadAssetsJsonUtil {
    /**
     * 将JSON文件读取成JSONObject
     * @param fileName
     * @param context
     * @return
     */
    fun getAreaList(fileName: String, context: Context): MutableList<AreaBean> {
        val jsonStr = getJson(fileName, context)
        //Log.d("ReadAssetsJsonUtil==", jsonStr)
        val gson = Gson()
        val type = object : TypeToken<MutableList<AreaBean?>?>() {}.type
        val mAreaBeans = gson.fromJson<MutableList<AreaBean>>(jsonStr, type)
        // 根据拼音为数组进行排序
        //Collections.sort(mAreaBeans, ComparatorPY())
        return mAreaBeans
    }



    fun getJson(fileName: String, context: Context): String {
        val stringBuilder = StringBuilder()
        try {
            //获取assets资源管理器
            val assetManager = context.assets
            //通过管理器打开文件并读取
            val bf = BufferedReader(
                InputStreamReader(
                    assetManager.open(fileName)
                )
            )
            var line: String?
            while (bf.readLine().also { line = it } != null) {
                stringBuilder.append(line)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return stringBuilder.toString()
    }
}